package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "InspectionSystemServlet", value = "/InspectionSystemServlet")
public class InspectionSystemServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://172.18.64.254:3306/三人行?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
    private static final String DB_USER = "webdb";
    private static final String DB_PASSWORD = "webdb";

    // 获取数据库连接（复用）
    private Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new SQLException("JDBC驱动加载失败", e);
        }
        return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
    }

    // 创建巡检任务（接收消防设备管理系统的数据）
    private void createInspectionTask(Map<String, String> paramMap) throws SQLException {
        String sql = "INSERT INTO inspection_task " +
                "(equipment_id, equipment_no, equipment_status, task_status) " +
                "VALUES (?, ?, ?, '待执行')";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, Integer.parseInt(paramMap.get("equipmentId")));
            pstmt.setString(2, paramMap.get("equipmentNo"));   // 存储提交的设备编号
            pstmt.setString(3, paramMap.get("equipmentStatus"));// 存储提交的设备状态
            pstmt.executeUpdate();
        }
    }

    // 查询所有巡检任务
    private List<Map<String, Object>> listInspectionTasks() throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "SELECT " +
                "t.id, t.equipment_id, t.equipment_no, t.equipment_status, " +
                "t.checker_id, t.task_status, t.create_time, " +
                "ds.name AS checker_name " +  // 关联duty_staff表的name字段
                "FROM inspection_task t " +
                "LEFT JOIN duty_staff ds ON t.checker_id = ds.id " + // 关联duty_staff表
                "ORDER BY t.create_time DESC";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", rs.getInt("id"));
                map.put("equipmentId", rs.getInt("equipment_id"));
                map.put("equipmentNo", rs.getString("equipment_no"));
                map.put("equipmentStatus", rs.getString("equipment_status"));
                map.put("checkerId", rs.getInt("checker_id"));
                map.put("checkerName", rs.getString("checker_name")); // 人员姓名
                map.put("taskStatus", rs.getString("task_status"));
                map.put("createTime", sdf.format(rs.getTimestamp("create_time")));
                list.add(map);
            }
        }
        return list;
    }

    // 根据ID查询单个巡检任务
    private List<Map<String, Object>> getTaskById(int id) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "SELECT " +
                "t.id, t.equipment_id, t.equipment_no, t.equipment_status, " +
                "t.checker_id, t.task_status, t.create_time, " +
                "ds.name AS checker_name " +  // 关联duty_staff表的name字段
                "FROM inspection_task t " +
                "LEFT JOIN duty_staff ds ON t.checker_id = ds.id " + // 关联duty_staff表
                "WHERE t.id = ?";  // 关键：添加ID条件

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            if (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", rs.getInt("id"));
                map.put("equipmentId", rs.getInt("equipment_id"));
                map.put("equipmentNo", rs.getString("equipment_no"));
                map.put("equipmentStatus", rs.getString("equipment_status"));
                map.put("checkerId", rs.getInt("checker_id"));
                map.put("checkerName", rs.getString("checker_name")); // 人员姓名
                map.put("taskStatus", rs.getString("task_status"));
                map.put("createTime", sdf.format(rs.getTimestamp("create_time")));
                list.add(map);
            }
        }
        return list;
    }

    // 更新巡检任务（分配人员、修改状态等）
    private void updateInspectionTask(Map<String, String> paramMap) throws SQLException {
        String sql = "UPDATE inspection_task " +
                "SET checker_id = ?, task_status = ? " +
                "WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, Integer.parseInt(paramMap.get("checkerId")));
            pstmt.setString(2, paramMap.get("taskStatus"));
            pstmt.setInt(3, Integer.parseInt(paramMap.get("id")));
            pstmt.executeUpdate();
        }
    }

    // 删除巡检任务
    private void deleteInspectionTask(int id) throws SQLException {
        String sql = "DELETE FROM inspection_task WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    }

    // 查询所有检查人员（用于下拉选择）
    private List<Map<String, Object>> listCheckers() throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "SELECT id, name FROM duty_staff"; // 查询duty_staff表的id和name字段
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", rs.getInt("id"));
                map.put("name", rs.getString("name")); // 对应duty_staff表的name字段
                list.add(map);
            }
        }
        return list;
    }

    // 处理GET请求（查询任务、查询人员）
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");

        try {
            if ("listTasks".equals(action)) {
                // 查询巡检任务列表
                List<Map<String, Object>> tasks = listInspectionTasks();
                out.println(toJsonArray(tasks));
            } else if ("getTaskById".equals(action)) { // 新增：根据ID查询单个任务
                String idStr = request.getParameter("id");
                if (idStr == null || idStr.isEmpty()) {
                    throw new IllegalArgumentException("缺少参数: id");
                }
                int taskId = Integer.parseInt(idStr);
                List<Map<String, Object>> task = getTaskById(taskId);
                out.println(toJsonArray(task));
            } else if ("listCheckers".equals(action)) {
                // 查询检查人员（用于下拉选择）
                List<Map<String, Object>> checkers = listCheckers();
                out.println(toJsonArray(checkers));
            } else if ("delete".equals(action)) {
                // 删除任务
                String idStr = request.getParameter("id");
                if (idStr == null || idStr.isEmpty()) {
                    throw new IllegalArgumentException("缺少参数: id");
                }
                deleteInspectionTask(Integer.parseInt(idStr));
                out.println("{\"success\": true}");
            } else {
                out.println("{\"error\": \"无效的操作(action)\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }

    // 处理POST请求（创建任务、更新任务）
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");

        try {
            if ("create".equals(action)) {
                // 接收消防设备管理系统提交的数据
                String equipmentId = request.getParameter("equipmentId");
                String equipmentNo = request.getParameter("equipmentNo");
                String equipmentStatus = request.getParameter("equipmentStatus");

                if (equipmentId == null || equipmentNo == null || equipmentStatus == null) {
                    throw new IllegalArgumentException("参数不完整");
                }

                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("equipmentId", equipmentId);
                paramMap.put("equipmentNo", equipmentNo);
                paramMap.put("equipmentStatus", equipmentStatus);

                createInspectionTask(paramMap);
                out.println("{\"success\": true}");
            } else if ("update".equals(action)) {
                // 更新任务（分配人员、修改状态）
                String id = request.getParameter("id");
                String checkerId = request.getParameter("checkerId");
                String taskStatus = request.getParameter("taskStatus");

                if (id == null || checkerId == null || taskStatus == null) {
                    throw new IllegalArgumentException("参数不完整");
                }

                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("id", id);
                paramMap.put("checkerId", checkerId);
                paramMap.put("taskStatus", taskStatus);

                updateInspectionTask(paramMap);
                out.println("{\"success\": true}");
            } else {
                out.println("{\"error\": \"无效的操作(action)\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }

    // JSON 转换工具（复用）
    private String toJson(Map<String, Object> map) {
        StringBuilder json = new StringBuilder("{");
        boolean first = true;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) json.append(",");
            json.append("\"").append(entry.getKey()).append("\":");
            if (entry.getValue() instanceof String) {
                json.append("\"").append(entry.getValue()).append("\"");
            } else {
                json.append(entry.getValue());
            }
            first = false;
        }
        json.append("}");
        return json.toString();
    }

    private String toJsonArray(List<Map<String, Object>> list) {
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) json.append(",");
            json.append(toJson(list.get(i)));
        }
        json.append("]");
        return json.toString();
    }
}